package com.zbh.uexam.service.impl;

import com.zbh.uexam.domain.TextContent;
import com.zbh.uexam.domain.enums.ExamPaperTypeEnum;
import com.zbh.uexam.domain.enums.QuestionTypeEnum;
import com.zbh.uexam.domain.exam.ExamPaperQuestionItemObject;
import com.zbh.uexam.domain.exam.ExamPaperTitleItemObject;
import com.zbh.uexam.domain.other.KeyValue;
import com.zbh.uexam.exception.BusinessException;
import com.zbh.uexam.repository.ExamPaperMapper;
import com.zbh.uexam.repository.QuestionMapper;
import com.zbh.uexam.service.ExamPaperService;
import com.zbh.uexam.service.QuestionService;
import com.zbh.uexam.service.SubjectService;
import com.zbh.uexam.service.TextContentService;
import com.zbh.uexam.service.enums.ActionEnum;
import com.zbh.uexam.utility.*;
import com.zbh.uexam.viewmodel.admin.exam.ExamPaperEditRequestVM;
import com.zbh.uexam.viewmodel.admin.exam.ExamPaperPageRequestVM;
import com.zbh.uexam.viewmodel.admin.exam.ExamPaperTitleItemVM;
import com.zbh.uexam.viewmodel.admin.question.QuestionEditRequestVM;
import com.zbh.uexam.viewmodel.student.dashboard.PaperFilter;
import com.zbh.uexam.viewmodel.student.dashboard.PaperInfo;
import com.zbh.uexam.viewmodel.student.exam.ExamPaperPageVM;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbh.uexam.domain.ExamPaper;
import com.zbh.uexam.domain.Question;
import com.zbh.uexam.domain.User;
import com.zbh.uexam.viewmodel.student.exam.GenerateTrainingExamPaperVM;
import com.zbh.uexam.viewmodel.student.exam.SearchTrainingExamPaperParam;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.modelmapper.internal.util.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ExamPaperServiceImpl extends BaseServiceImpl<ExamPaper> implements ExamPaperService {

    protected final static ModelMapper modelMapper = ModelMapperSingle.Instance();
    private final ExamPaperMapper examPaperMapper;
    private final QuestionMapper questionMapper;
    private final TextContentService textContentService;
    private final QuestionService questionService;
    private final SubjectService subjectService;

    @Autowired
    public ExamPaperServiceImpl(ExamPaperMapper examPaperMapper, QuestionMapper questionMapper, TextContentService textContentService, QuestionService questionService, SubjectService subjectService) {
        super(examPaperMapper);
        this.examPaperMapper = examPaperMapper;
        this.questionMapper = questionMapper;
        this.textContentService = textContentService;
        this.questionService = questionService;
        this.subjectService = subjectService;
    }


    @Override
    public PageInfo<ExamPaper> page(ExamPaperPageRequestVM requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), requestVM.getSort()).doSelectPageInfo(() ->
                examPaperMapper.page(requestVM));
    }

    @Override
    public PageInfo<ExamPaper> taskExamPage(ExamPaperPageRequestVM requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                examPaperMapper.taskExamPage(requestVM));
    }

    @Override
    public PageInfo<ExamPaper> studentPage(ExamPaperPageVM requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id desc").doSelectPageInfo(() ->
                examPaperMapper.studentPage(requestVM));
    }

    @Override
    public  PageInfo<ExamPaper> searchTrainingPage(SearchTrainingExamPaperParam searchTrainingExamPaperParam) {
        return PageHelper.startPage(searchTrainingExamPaperParam.getPageIndex(), searchTrainingExamPaperParam.getPageSize(), searchTrainingExamPaperParam.getSort()).doSelectPageInfo(() ->
                examPaperMapper.searchTrainingExamPaper(searchTrainingExamPaperParam));
    }


    @Override
    @Transactional
    public ExamPaper savePaperFromVM(ExamPaperEditRequestVM examPaperEditRequestVM, User user) {
        ActionEnum actionEnum = (examPaperEditRequestVM.getId() == null) ? ActionEnum.ADD : ActionEnum.UPDATE;
        Date now = new Date();
        List<ExamPaperTitleItemVM> titleItemsVM = examPaperEditRequestVM.getTitleItems();
        List<ExamPaperTitleItemObject> frameTextContentList = frameTextContentFromVM(titleItemsVM);
        String frameTextContentStr = JsonUtil.toJsonStr(frameTextContentList);


        ExamPaper examPaper;
        if (actionEnum == ActionEnum.ADD) {
            examPaper = modelMapper.map(examPaperEditRequestVM, ExamPaper.class);
            TextContent frameTextContent = new TextContent(frameTextContentStr, now);
            textContentService.insertByFilter(frameTextContent);
            examPaper.setFrameTextContentId(frameTextContent.getId());
            examPaper.setCreateTime(now);
            examPaper.setCreateUser(user.getId());
            examPaper.setDeleted(false);
            examPaperFromVM(examPaperEditRequestVM, examPaper, titleItemsVM);
            examPaperMapper.insertSelective(examPaper);
        } else {
            examPaper = examPaperMapper.selectByPrimaryKey(examPaperEditRequestVM.getId());
            TextContent frameTextContent = textContentService.selectById(examPaper.getFrameTextContentId());
            frameTextContent.setContent(frameTextContentStr);
            textContentService.updateByIdFilter(frameTextContent);
            modelMapper.map(examPaperEditRequestVM, examPaper);
            examPaperFromVM(examPaperEditRequestVM, examPaper, titleItemsVM);
            examPaperMapper.updateByPrimaryKeySelective(examPaper);
        }
        return examPaper;
    }

    @Override
    public ExamPaperEditRequestVM examPaperToVM(Integer id) {
        ExamPaper examPaper = examPaperMapper.selectByPrimaryKey(id);
        ExamPaperEditRequestVM vm = modelMapper.map(examPaper, ExamPaperEditRequestVM.class);
        vm.setLevel(examPaper.getGradeLevel());
        TextContent frameTextContent = textContentService.selectById(examPaper.getFrameTextContentId());
        List<ExamPaperTitleItemObject> examPaperTitleItemObjects = JsonUtil.toJsonListObject(frameTextContent.getContent(), ExamPaperTitleItemObject.class);
        List<Integer> questionIds = examPaperTitleItemObjects.stream()
                .flatMap(t -> t.getQuestionItems().stream()
                        .map(q -> q.getId()))
                .collect(Collectors.toList());
        List<Question> questions = questionMapper.selectByIds(questionIds);
        List<ExamPaperTitleItemVM> examPaperTitleItemVMS = examPaperTitleItemObjects.stream().map(t -> {
            ExamPaperTitleItemVM tTitleVM = modelMapper.map(t, ExamPaperTitleItemVM.class);
            List<QuestionEditRequestVM> questionItemsVM = t.getQuestionItems().stream().map(i -> {
                Question question = questions.stream().filter(q -> q.getId().equals(i.getId())).findFirst().get();
                QuestionEditRequestVM questionEditRequestVM = questionService.getQuestionEditRequestVM(question);
                questionEditRequestVM.setItemOrder(i.getItemOrder());
                return questionEditRequestVM;
            }).collect(Collectors.toList());
            tTitleVM.setQuestionItems(questionItemsVM);
            return tTitleVM;
        }).collect(Collectors.toList());
        vm.setTitleItems(examPaperTitleItemVMS);
        vm.setScore(ExamUtil.scoreToVM(examPaper.getScore()));
        if (ExamPaperTypeEnum.TimeLimit == ExamPaperTypeEnum.fromCode(examPaper.getPaperType())) {
            List<String> limitDateTime = Arrays.asList(DateTimeUtil.dateFormat(examPaper.getLimitStartTime()), DateTimeUtil.dateFormat(examPaper.getLimitEndTime()));
            vm.setLimitDateTime(limitDateTime);
        }
        return vm;
    }

    @Override
    public List<ExamPaper> indexPaper(PaperFilter paperFilter) {
        return examPaperMapper.indexPaper(paperFilter);
    }


    @Override
    public Integer selectAllCount() {
        return examPaperMapper.selectAllCount();
    }

    @Override
    public List<Integer> selectMothCount() {
        Date startTime = DateTimeUtil.getMonthStartDay();
        Date endTime = DateTimeUtil.getMonthEndDay();
        List<KeyValue> mouthCount = examPaperMapper.selectCountByDate(startTime, endTime);
        List<String> mothStartToNowFormat = DateTimeUtil.MothStartToNowFormat();
        return mothStartToNowFormat.stream().map(md -> {
            KeyValue keyValue = mouthCount.stream().filter(kv -> kv.getName().equals(md)).findAny().orElse(null);
            return null == keyValue ? 0 : keyValue.getValue();
        }).collect(Collectors.toList());
    }

    @Override
    public String generateTrainingExamPaper(GenerateTrainingExamPaperVM generateTrainingExamPaperVM, User user) {
        // Integer total = generateTrainingExamPaperVM.getSingleChoice() + generateTrainingExamPaperVM.getMultipleChoice()
        //         + generateTrainingExamPaperVM.getJudgment() + generateTrainingExamPaperVM.getGapFilling();
        log.info("generateTrainingExamPaperVM:{}",generateTrainingExamPaperVM);
        Integer difficult = generateTrainingExamPaperVM.getDifficult();
        // 找到对应学科的题目
        List<Question> questions = questionService.selectBySubjectId(Integer.parseInt(generateTrainingExamPaperVM.getSubjectId()));
        // 从题目中筛选对应年级
        questions = questions.stream().filter(x -> x.getGradeLevel().equals(user.getUserLevel())).collect(Collectors.toList());
        log.info("questions:{}",JsonUtil.toJsonStr(questions));
        // 分类 1.单选题  2.多选题  3.判断题 4.填空题 5.简答题
        Map<Integer, List<Question>> groupByQuestionType = questions.stream().collect(Collectors.groupingBy(Question::getQuestionType));
        log.info("groupByQuestionType:{}", groupByQuestionType);
        // 权重列表
        List<Integer> difficultWeightList = WeightUtil.getDifficultWeightList(generateTrainingExamPaperVM.getDifficult());
        // 试卷
        ExamPaperEditRequestVM examPaperEditRequestVM = new ExamPaperEditRequestVM();
        examPaperEditRequestVM.setPaperType(ExamPaperTypeEnum.Train.getCode());
        examPaperEditRequestVM.setLevel(user.getUserLevel());
        examPaperEditRequestVM.setSubjectId(Integer.parseInt(generateTrainingExamPaperVM.getSubjectId()));
        examPaperEditRequestVM.setSuggestTime(1440);
        examPaperEditRequestVM.setLimitDateTime(null);
        examPaperEditRequestVM.setName("训练试卷"+DateTimeUtil.dateFormat(new Date()).replaceAll("[-:\\s]+", ""));
        List<ExamPaperTitleItemVM> titleItems = new ArrayList<>();
        if (generateTrainingExamPaperVM.getSingleChoice() > 0) {
            if (!groupByQuestionType.containsKey(QuestionTypeEnum.SingleChoice.getCode()) || groupByQuestionType.get(QuestionTypeEnum.SingleChoice.getCode()).size() <  generateTrainingExamPaperVM.getSingleChoice()) {
                throw new BusinessException("单选题数量不够");
            }
        }
        if (generateTrainingExamPaperVM.getSingleChoice() > 0) {
            if (!groupByQuestionType.containsKey(QuestionTypeEnum.SingleChoice.getCode()) || groupByQuestionType.get(QuestionTypeEnum.SingleChoice.getCode()).size() <  generateTrainingExamPaperVM.getSingleChoice()) {
                throw new BusinessException("单选题数量不够");
            }
        }
        if (generateTrainingExamPaperVM.getMultipleChoice() > 0) {
            if (!groupByQuestionType.containsKey(QuestionTypeEnum.MultipleChoice.getCode()) || groupByQuestionType.get(QuestionTypeEnum.MultipleChoice.getCode()).size() <  generateTrainingExamPaperVM.getMultipleChoice()) {
                throw new BusinessException("多选题数量不够");
            }
        }
        if (generateTrainingExamPaperVM.getJudgment() > 0) {
            if (!groupByQuestionType.containsKey(QuestionTypeEnum.TrueFalse.getCode()) || groupByQuestionType.get(QuestionTypeEnum.TrueFalse.getCode()).size() <  generateTrainingExamPaperVM.getJudgment()) {
                throw new BusinessException("判断题数量不够");
            }
        }
        if (generateTrainingExamPaperVM.getGapFilling() > 0) {
            if (!groupByQuestionType.containsKey(QuestionTypeEnum.GapFilling.getCode()) || groupByQuestionType.get(QuestionTypeEnum.GapFilling.getCode()).size() <  generateTrainingExamPaperVM.getGapFilling()) {
                throw new BusinessException("填空题数量不够");
            }
        }
        for (Map.Entry<Integer, List<Question>> entry : groupByQuestionType.entrySet()) {
            // List<Integer> curDifficultWeightList = new ArrayList<>(difficultWeightList);
            List<Integer> curDifficultWeightList = null;
            log.info("entry.value:{}", entry.getValue());
            try {
                curDifficultWeightList = (List<Integer>) CloneUtil.deepClone(difficultWeightList);
            } catch (Exception e) {
                log.error("深度拷贝失败");
                throw new BusinessException("生成试卷时出现异常，请联系管理员");
            }
            ExamPaperTitleItemVM examPaperTitleItemVM = new ExamPaperTitleItemVM();
            List<Question> randomQuestionList = new ArrayList<>();
            if (entry.getKey().equals(QuestionTypeEnum.SingleChoice.getCode())) {
                if (generateTrainingExamPaperVM.getSingleChoice() == 0) {
                    continue;
                }
                List<Question> singleChoice = entry.getValue();
                randomQuestionList = randomGenerateExamPaper(singleChoice, generateTrainingExamPaperVM.getSingleChoice(), curDifficultWeightList, difficult);
                examPaperTitleItemVM.setName("单选题");
            } else if (entry.getKey().equals(QuestionTypeEnum.MultipleChoice.getCode())) {
                if (generateTrainingExamPaperVM.getMultipleChoice() == 0) {
                    continue;
                }
                List<Question> multipleChoice = entry.getValue();
                randomQuestionList = randomGenerateExamPaper(multipleChoice, generateTrainingExamPaperVM.getMultipleChoice(), curDifficultWeightList, difficult);
                examPaperTitleItemVM.setName("多选题");
            } else if (entry.getKey().equals(QuestionTypeEnum.TrueFalse.getCode())) {
                if (generateTrainingExamPaperVM.getJudgment() == 0) {
                    continue;
                }
                List<Question> trueFalse = entry.getValue();
                randomQuestionList = randomGenerateExamPaper(trueFalse, generateTrainingExamPaperVM.getJudgment(), curDifficultWeightList, difficult);
                examPaperTitleItemVM.setName("判断题");
            } else if (entry.getKey().equals(QuestionTypeEnum.GapFilling.getCode())) {
                if (generateTrainingExamPaperVM.getGapFilling() == 0) {
                    continue;
                }
                List<Question> gapFilling = entry.getValue();
                randomQuestionList = randomGenerateExamPaper(gapFilling, generateTrainingExamPaperVM.getGapFilling(), curDifficultWeightList, difficult);
                examPaperTitleItemVM.setName("填空题");
            } else if (entry.getKey().equals(QuestionTypeEnum.ShortAnswer.getCode())) {
                if (generateTrainingExamPaperVM.getShortAnswer() == 0) {
                    continue;
                }
                List<Question> shortAnswer = entry.getValue();
                randomQuestionList = randomGenerateExamPaper(shortAnswer, generateTrainingExamPaperVM.getShortAnswer(), curDifficultWeightList, difficult);
                examPaperTitleItemVM.setName("简答题");
            }
            examPaperTitleItemVM.setQuestionItems(randomQuestionList.stream().map(questionService::getQuestionEditRequestVM).collect(Collectors.toList()));
            titleItems.add(examPaperTitleItemVM);
        }
        examPaperEditRequestVM.setTitleItems(titleItems);
        savePaperFromVM(examPaperEditRequestVM, user);
        return examPaperEditRequestVM.getName();
    }

    public List<Question> randomGenerateExamPaper(List<Question> questions, Integer requiredNum, List<Integer> curDifficultWeightList, Integer requiredDifficult) {
        log.info("curDifficultWeightList初始为:{}", curDifficultWeightList);
        log.info("requiredNum初始为:{}", requiredNum);
        int i = 0;
        // 平均难度误差1以内
        double deviation = 0.5f;
        double minDif = Double.MAX_VALUE;
        Collections.shuffle(questions);
        List<Question> bestRandomChoice =  new ArrayList<>();
        // 最多三次取最佳
        while(i < 3) {
            List<Integer> tempCurDifficultWeightList = new ArrayList<>(curDifficultWeightList);
            List<Question> randomChoice = new ArrayList<>();
            Map<Integer, List<Question>> groupByDifficult  = questions.stream().collect(Collectors.groupingBy(Question::getDifficult));
            while (randomChoice.size() < requiredNum) {
                log.info("randomChoice.size:{}", randomChoice.size());
                int randomDifficult = WeightUtil.getDifficultRandomByWeight(tempCurDifficultWeightList);
                if (!CollectionUtils.isEmpty(groupByDifficult.get(randomDifficult))) {
                    randomChoice.add(groupByDifficult.get(randomDifficult).get(0));
                    groupByDifficult.get(randomDifficult).remove(0);
                } else {
                    // 数量不够就将权重置为0
                    // 返回的难度是下标+1
                    tempCurDifficultWeightList.set(randomDifficult - 1, 0);
                }
            }
            double average = randomChoice.stream().mapToInt((Question::getDifficult)).sum() / (requiredNum * 1.0);
            // 如果满足误差的话，就直接返回
            double dif = Math.abs(average - requiredDifficult.doubleValue());
            if (dif < deviation) {
                return randomChoice;
            }
            // 如果不满足误差，三次取最佳
            if (dif < minDif) {
                bestRandomChoice = new ArrayList<>(randomChoice);
                minDif = dif;
            }
            i++;
        }
        return bestRandomChoice;
    }

    private void examPaperFromVM(ExamPaperEditRequestVM examPaperEditRequestVM, ExamPaper examPaper, List<ExamPaperTitleItemVM> titleItemsVM) {
        Integer gradeLevel = subjectService.levelBySubjectId(examPaperEditRequestVM.getSubjectId());
        Integer questionCount = titleItemsVM.stream()
                .mapToInt(t -> t.getQuestionItems().size()).sum();
        Integer score = titleItemsVM.stream().
                flatMapToInt(t -> t.getQuestionItems().stream()
                        .mapToInt(q -> ExamUtil.scoreFromVM(q.getScore()))
                ).sum();

        Integer difficult = titleItemsVM.stream().flatMapToInt(t -> t.getQuestionItems().stream().mapToInt(QuestionEditRequestVM::getDifficult)).sum();

        difficult = Math.round(Float.parseFloat(String.valueOf(difficult)) / questionCount);
        examPaper.setQuestionCount(questionCount);
        examPaper.setScore(score);
        examPaper.setGradeLevel(gradeLevel);
        examPaper.setDifficult(difficult);
        List<String> dateTimes = examPaperEditRequestVM.getLimitDateTime();
        if (ExamPaperTypeEnum.TimeLimit == ExamPaperTypeEnum.fromCode(examPaper.getPaperType())) {
            examPaper.setLimitStartTime(DateTimeUtil.parse(dateTimes.get(0), DateTimeUtil.STANDER_FORMAT));
            examPaper.setLimitEndTime(DateTimeUtil.parse(dateTimes.get(1), DateTimeUtil.STANDER_FORMAT));
        }
    }

    private List<ExamPaperTitleItemObject> frameTextContentFromVM(List<ExamPaperTitleItemVM> titleItems) {
        AtomicInteger index = new AtomicInteger(1);
        return titleItems.stream().map(t -> {
            ExamPaperTitleItemObject titleItem = modelMapper.map(t, ExamPaperTitleItemObject.class);
            List<ExamPaperQuestionItemObject> questionItems = t.getQuestionItems().stream()
                    .map(q -> {
                        ExamPaperQuestionItemObject examPaperQuestionItemObject = modelMapper.map(q, ExamPaperQuestionItemObject.class);
                        examPaperQuestionItemObject.setItemOrder(index.getAndIncrement());
                        return examPaperQuestionItemObject;
                    })
                    .collect(Collectors.toList());
            titleItem.setQuestionItems(questionItems);
            return titleItem;
        }).collect(Collectors.toList());
    }

}
